package leetcode.datastructure.stack;

import java.util.*;

public class Program20bracket {

    public Program20bracket() {
    }

    public boolean isValid(String s) {
        if ((s.length() | 1) == 1) {
            return false;
        }
        List<Character> leftBrackets = Arrays.asList('(','{','[');
        if (!leftBrackets.contains(s.charAt(0))) {
            return false;
        }
        Stack<Character> stack = new Stack<>();
        stack.push(s.charAt(0));
        for (int i = 1; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (leftBrackets.contains(ch)) {
                stack.push(ch);
            } else {
                if (stack.empty()) {
                    return false;
                }
                char pop = stack.pop();
                switch (ch) {
                    case ')':
                        if (pop != '(') {
                            return false;
                        }
                        break;
                    case '}':
                        if (pop != '{') {
                            return false;
                        }
                        break;
                    case ']':
                        if (pop != '[') {
                            return false;
                        }
                        break;
                    default:
                        return false;
                }
            }
        }
        return stack.empty();
    }

    public static void main(String[] args) {
        Program20bracket myStack = new Program20bracket();
        System.out.println(myStack.isValid("()")); // 返回 true
        System.out.println(myStack.isValid("()[]{}")); // 返回 true
        System.out.println(myStack.isValid("(]")); // 返回 false
        System.out.println(myStack.isValid("(){}}{")); // 返回 false
    }
}
